<template>
	<div class="wrapper">
		<top-bar>
			<template v-slot:title>
				{{ $t("Coins TO Cash") }}
			</template>
		</top-bar>
		<abnormal-page v-if="pageError" @retry="getData"></abnormal-page>
        <div v-else class="container">
			<div class="main">
				<balance-panel />
				<div class="channel module">
					<div class="title">{{ typeText }}</div>
					<ul class="select">
						<li
							v-for="(item, index) in withdrawList"
							:key="index"
							:class="[
								'select-item',
								`${channelInfo?.type}`,
								{ active: index === selectActive },
							]"
							@click="selectItem(index)"
						>
							<div class="main">
								<div class="icon"></div>
								<div class="money">
									{{ vueState.countryInfo.currencySymbol
									}}{{ item.money }}
								</div>
							</div>
							<div class="footer">
								<div class="coin-num">{{ item.coin }}</div>
							</div>
						</li>
					</ul>
				</div>
				<div class="desc module">
					<div class="desc module">
                    <div class="title">{{$t('Description')}}</div>
                    <div class="tips">{{$t('WithDrawDes1')}}</div>
                    <div class="content">{{$t('WithDrawDes2')}}</div>
                    <div class="content">{{$t('WithDrawDes3')}}</div>
                    <div class="content">{{$t('A 10% rate will be charged for each order')}}</div>
                </div>
				</div>
			</div>
			<div class="footer">
				<div
					class="button"
					:style="{
						bottom:
							0.32 * fsize +
							(vueState.pageStyle.tabBarHeight || 0) +
							'px',
					}"
					@click="clickWithdraw"
				>
					{{ $t("Withdraw") }}
				</div>
			</div>
		</div>
		<withdraw-pix-modal
			v-model:show="withdrawPixModalData.show"
			@submit="withdrawPixModalData.submit"
			:type="typeText"
		></withdraw-pix-modal>
		<withdraw-modal
			v-model:show="withdrawModalData.show"
			@submit="withdrawModalData.submit"
			:type="typeText"
		></withdraw-modal>
		<vip-modal
			v-model:show="vipModalData.show"
			@submit="vipModalData.submit"
		></vip-modal>
		<failure-modal v-model:show="failureModalData.show"/>

		<van-dialog
			class="confirm-dialog"
			width="2.95rem"
			v-model:show="withdrawConfirmModalData.show"
			@confirm="withdrawConfirmModalData.confirm"
			show-cancel-button
			:confirm-button-text="$t('Confirm')"
			confirm-button-color="#F5B53F"
			:cancel-button-text="$t('Cancel')"
			cancel-button-color="#9C9DA6"
		>
			<template #default>
				<div :class="['confirm-dialog-header', `${channelInfo?.type}`]"></div>
				<div class="confirm-dialog-container">
					<div class="title">{{ $t("Dear") }} {{ realName }}:</div>
					<!-- <div class="content">
						{{ $t("withdrawConfirm")(typeText) }} (<span>{{
							account
						}}</span
						>)?
					</div> -->
                    <div class="content">{{$t('Are you sure to cash out to $m Account',[{msg:'$m',val:info.typeText}])}} (<span>{{info.account}}</span>)?</div>
				</div>
			</template>
		</van-dialog>
        <!--to:langlang  -s-->
        <WithdrawToBankCardModal v-model:show="withdrawToBankCardModalData.show" @submit="withdrawToBankCardModalData.submit" />
        <!--to:langlang  -e-->
	</div>
</template>
<script>
import {QuickBalanceApi} from '@@/api/quick.js'
import {BalanceApi} from '@@/api/api.js'
import {useWithdrawLimit} from './hooks/useWithdrawLimit.js'
import {reactive,toRefs,onUnmounted,inject, onMounted,computed,getCurrentInstance,ref, watch} from 'vue'
import {debounce,checkObjectEmpty} from '@@/utils/common.js' 
import { useRouter } from 'vue-router'
import { Toast } from 'vant'
import WithdrawModal from '../../components/Modal/WithdrawModal.vue'
import WithdrawPixModal from '../../components/Modal/WithdrawPixModal.vue'
import VipModal from '../../components/Modal/VipModal.vue'
import FailureModal from './modal/failureModal.vue'
import BalancePanel from './components/balancePanel.vue'
// to:langlang   -s
import WithdrawToBankCardModal from '../../components/Modal/WithdrawToBankCardModal.vue'
// to:langlang   -e
export default {
    components:{
        WithdrawModal,
        VipModal,
        WithdrawPixModal,
        FailureModal,
        BalancePanel,
        WithdrawToBankCardModal
    },
    props:{
        channel:{
            default:'{}'
        }
    },
    setup(props) {
        const {proxy} = getCurrentInstance()
        const vueState = inject('vueState')
        const router = useRouter()
        const {vipModalData,getLimitInfo,switchWithdraw,failureModalData,state:limitState} = useWithdrawLimit()
        const state = reactive({
            pageError:false,
            selectActive:0,
            account:'',
            realName:'',
            phone:'',
            email:'',
            documentId:'',
            offerId:'',
            clickId:'',
            fsize:window.fsize,
            channelId:'',
            type:'',
            withdrawList:[],
            bankName: '',   // to:langlang  添加属性
            bankLinkNo: '' // to:langlang   添加属性
        })
        const channelInfo = computed(()=>{
            return checkObjectEmpty(JSON.parse(props.channel)) ? vueState.pageInfo.withdrawChannel : JSON.parse(props.channel) 
        })
		const withdrawItem = computed(()=>{
			return state.withdrawList[state.selectActive]
		})
        const typeText = computed(()=>{
            switch (channelInfo.value?.type) {
                case 'paypal':
                    return 'PayPal'
                case 'paytm':
                    return 'Paytm' 
                case 'pix':
                    return 'PIX'
                case 'upi':
                    return 'UPI' 
                case 'BANK': //to:langlang  -s   添加bank类型///把bankCard 修改为 bank
                    return 'BANK'   //to:langlang  -s   添加bank类型  ///把bankCard 修改为 bank    
                default:
                    return ''
            }
        })
        
        const withdrawConfirmModalData = reactive({
            show:false,
            info:{
                type:'',
                typeText:'',
                account:'',
                realName:''
            },
            showModal:()=>{
                withdrawConfirmModalData.info.realName = state.realName
                withdrawConfirmModalData.info.account = state.account
                withdrawConfirmModalData.info.type = channelInfo.value.type
                withdrawConfirmModalData.info.typeText = typeText.value
                withdrawConfirmModalData.show = true
            },
            confirm:()=>{
                withdraw()
            }
        })
        const withdrawModalData = reactive({
            show:false,
            showModal:()=>{
                withdrawModalData.show = true
            },
            submit:debounce((field)=> {
                const {name,email,account} = field     //lsy fixed
                state.account = `${vueState.countryInfo.areaCode}${account.model}`
                state.phone = `${vueState.countryInfo.areaCode}${account.model}` 
                state.realName = name.model
                state.email = email.model
                // state.bankLinkNo = branchCode.model     //lsy fixed
                if(name.state && email.state && account.state){     //lsy fixed
                    withdrawConfirmModalData.showModal()
                }
            },500)
        })

        const withdrawToBankCardModalData = reactive({
            show:false,
            showModal:()=>{
                withdrawModalData.show = true
            },
            submit:debounce((field)=> {
                //银行卡去空格
                const {PayeeEmail,PayeeName,bankCardNo,bankName,bankLinkNo,phone} = field
                // withdrawConfirmModalData.showModal()
                state.realName = PayeeName.model
                state.bankName = bankName.model
                state.email = PayeeEmail.model
                state.bankLinkNo = bankLinkNo.model.toLocaleUpperCase()
                state.account =  bankCardNo.model.trim()
                state.phone = `${vueState.countryInfo.areaCode}${phone.model}` 
                if(PayeeEmail.state && PayeeName.state && bankCardNo.state && bankName.state && bankLinkNo.state && phone.state){
                    withdrawConfirmModalData.showModal()
                }
            },500)
        })

        const withdrawPixModalData = reactive({
            show:false,
            submit:debounce((field,realAccount)=> {
                console.log(field,realAccount);
                const {name,email,documentId,phone} = field
                state.phone = `${vueState.countryInfo.areaCode}${phone.model}` 
                state.realName = name.model
                state.email = email.model
                state.account = realAccount
                state.documentId = documentId.model
                withdrawConfirmModalData.showModal()
            },500)
        })


        const getData = async()=> {
            Toast.loading({duration:0,message:`${proxy.$t('Loading')}...`})
            try{
                const {toBalanceRate:{channelRateVos=[]}} = await BalanceApi.WithdrawInfo({channelType:channelInfo.value?.type})
                state.pageError = false
                state.withdrawList = channelRateVos.map((item)=>{
                    return {
                        coin:item.coin,
                        money:item.money / 100
                    }
                })
                Toast.clear()
            }catch(e){
                state.pageError = true
                console.log(e);
                setTimeout(()=>{
                    Toast.clear()
                },3000)
            }
        }
        const withdraw = async ()=> {
            Toast.loading({duration:0,message:`${proxy.$t('Loading')}...`})
            try{
                await QuickBalanceApi.Withdraw({
                    convertCount:withdrawItem.value.coin,
                    bundleId:vueState.bundle,
                    channelId:channelInfo.value.channelId,
                    withdrawAccount:state.account,
                    type:channelInfo.value.type,
                    clickId:state.clickId,
                    offerId:state.offerId,
                    realName:state.realName,
                    documentId:state.documentId,
                    payeeMobile:state.phone,
                    payeeEmail:state.email, //to:langlang  -s 
                    bankName: state.bankName, //to:langlang  -s 
                    bankLinkNo: state.bankLinkNo //to:langlang  -s 
                })
                vueState.getBaseInfo()
                window.SDKPostMessage({
                    event:'h5_data_changed',
                    data:{
                        type:'balance'
                    }
                })
                window.trackEvent({pageTitle:`withdraw${typeText.value}page`,ev:'clicktowithdraw',remarks:`status:success,phone:${state.phone},amount:${withdrawItem.value.coin},account:${state.account}`})
                withdrawModalData.show = false
                withdrawPixModalData.show = false
                Toast.success(proxy.$t('Success'))
                window.SDKPostMessage({
                    event:'h5_open_page',
                    data:{
                        target:'reward_pop',
                        data:{
                            from:'withdraw',
                            coin:0,
                            cash:withdrawItem.value.money
                        }
                    }
                })
            }catch(e){
                window.trackEvent({pageTitle:`withdraw${typeText.value}page`,ev:'clicktowithdraw',remarks:'status:others'})
                console.log(e);
                if(e?.data?.code === 201021){
                    Toast(proxy.$t('You can apply after completing the first withdrawal'))
                }else if(e?.data?.code === 201022){
                    Toast.clear()
                    failureModalData.show = true
                    
                }   
                setTimeout(()=>{
                    Toast.clear()
                },3000)
            }
        }
        const selectItem = (index)=>{
            state.selectActive = index;
            if(index === 2){
                window.trackEvent({pageTitle:`withdraw${typeText.value}page`,ev:'clickGear3'})
            } 
        }
        const clickWithdraw = async()=> {
            // withdraw()
            // withdrawConfirmModalData.showModal()
            console.log(withdrawItem.value);
            // withdrawModalData.showModal()
            if(!vueState.pageInfo.mobile){
                window.SDKPostMessage({
                    event:'h5_open_page',
                    data:{
                        target:'bind_mobile',
                        data:{
                            page:'withdrawpage',
                            showEvent:'showwithdrawbind',
                            clickEvent:'clickwithdrawbind'
                        }
                    }
                })
                window.trackEvent({pageTitle:`withdraw${typeText.value}page`,ev:'clicktowithdraw2'})
                return
            }
            
            if(vueState.pageInfo.totalCoin < withdrawItem.value.coin){
                window.trackEvent({pageTitle:`withdraw${typeText.value}page`,ev:'clicktowithdraw2',remarks:'status:insufficient'})
                Toast(proxy.$t('Insufficient coins'))
                return false
            }
            await getLimitInfo()
            if(limitState.isNewWithdraw && state.selectActive ===2){
                Toast(proxy.$t('You can apply after completing the first withdrawal'))
                return
            }
            if(vueState.pageInfo.mobile && vueState.pageInfo.totalCoin >= withdrawItem.value.coin){
                if(switchWithdraw(channelInfo.value.flag)){
                    if(channelInfo.value.type === 'pix'){
                        withdrawPixModalData.show = true
                        window.trackEvent({pageTitle:`withdraw${typeText.value}page`,ev:'showtowithdraw'})
                    }
                    // to:langlang  -s
                    else if(channelInfo.value.type === 'BANK'){  
                        //todo:
                        withdrawToBankCardModalData.show = true
                    }else{
                        window.trackEvent({pageTitle:`withdraw${typeText.value}page`,ev:'showtowithdraw'})
                        withdrawModalData.showModal()
                    }
                }
                window.trackEvent({pageTitle:`withdraw${typeText.value}page`,ev:'clicktowithdraw2'})
            }
        }
        const goWithdrawHistory = ()=> {
            // router.push({name:'withdrawRecord'})
            if(!vueState.pageInfo.mobile){
                window.SDKPostMessage({
                    event:'h5_open_page',
                    data:{
                        target:'bind_mobile',
                        data:{
                            page:'withdrawpage',
                            showEvent:'showwithdrawbind',
                            clickEvent:'clickwithdrawbind'
                        }
                    }
                })
                return
            }
            router.push({name:'record'})
        }
        const getTaskInfo = (res)=> {
            const {offerId,clickId} = res.data
            state.offerId = offerId,
            state.clickId = clickId
            console.log('Withdraw',state);
        }
        watch(()=>failureModalData.show,(newVal)=>{
            if(newVal){
                window.trackEvent({pageTitle:'withdrawpage',ev:'showSwitchingPop',remarks:`Type=${channelInfo.value.type}`})
            }
        })
        onMounted(()=>{
            console.log(channelInfo.value);
            // initLottie()
            vueState.EventEmitter.immediately('afterRegist',getData,vueState.pageStatus.afterRegist)
            // window.AdSDK.addEventListener('ad_callback_h5',vueState.getBaseInfo)
            window.trackEvent({pageTitle:`withdraw${typeText.value}page`,ev:'showwithdraw'})
            window.AdSDK.addEventListener('ow_ad_task_h5',getTaskInfo)
            window.SDKPostMessage({
                event:'ow_h5_task_ad',
                data:{
                    task:'Withdraw',
                    type:1
                }
            })
        })
        onUnmounted(()=>{
            // window.AdSDK.removeEventListener('ad_callback_h5',vueState.getBaseInfo)
            window.AdSDK.removeEventListener('ow_ad_task_h5',getTaskInfo)
        })
        
        return {
            vueState,
            router,
            clickWithdraw,
            ...toRefs(state),
            withdrawModalData,
            withdrawConfirmModalData,
            goWithdrawHistory,
            getData,
            typeText,
            selectItem,
            vipModalData,
            withdrawPixModalData,
            channelInfo,
            failureModalData,
            withdrawToBankCardModalData   //to:langlang 
        }
    }
}
</script>
<style lang="less" scoped>
.confirm-dialog {
	&-header {
		height: 1rem;
		background-size: contain;
		position: relative;
		&.paytm {
			background-image: url(../../assets/images/Modal/withdraw_confirm_text_paytm.png);
		}
		&.paypal {
			background-image: url(../../assets/images/Modal/withdraw_confirm_text_paypal.png);
		}
		&.pix {
			background-image: url(../../assets/images/Modal/withdraw_confirm_text_pix.png);
		}
		.text {
			position: absolute;
			top: 0.3rem;
			left: 0.15rem;
			height: 0.5rem;
			width: 1.9rem;
			background: url(../../assets/images/Modal/withdraw_confirm_text_paytm.png)
				no-repeat center;
			background-size: contain;
		}
	}
	&-container {
		padding: 0.24rem 0.16rem;
		background-color: #fafcfe;
		font-size: 0.16rem;
		font-weight: 400;

		.title {
			line-height: 0.28rem;
			color: #121314;
		}
		.content {
			line-height: 0.28rem;
			margin-top: 0.12rem;
			color: #9c9da6;
			& > span {
				color: @theme-color;
			}
		}
	}
}
.wrapper {
	height: 100%;
	background-color: white;
	/deep/.van-dialog__cancel,
	/deep/.van-dialog__confirm {
		height: 0.56rem;
		font-size: 0.14rem;
	}
	/deep/.van-dialog__confirm {
		font-weight: 500;
		font-size: 0.16rem;
	}
	/deep/.van-dialog__header {
		padding: 0.32rem 0;
	}
	.container {
		height: 100%;
		padding-bottom: 0.88rem;
		overflow-y: auto;
		& > .header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0.12rem 0.1rem 0.12rem 0.16rem;
			font-size: 0.14rem;
			color: @theme-color;
			background-color: #c8fbd2;
			.text {
				line-height: 0.24rem;
				& > span {
					font-weight: bold;
				}
			}
			.arrow {
				height: 0.24rem;
				width: 0.24rem;
				background: url(../../assets/images/right_arrow_green.png)
					no-repeat center;
				background-size: contain;
			}
		}
		& > .main {
			padding: 0.18rem 0.16rem 0;
			.channel {
				.select {
					margin-top: 0.12rem;
					display: flex;
					justify-content: space-between;
					&-item {
						background: #f8f8f8;
						&.active {
							background: #fef7e8;
							&.paytm {
								.icon {
									opacity: 1;
								}
							}
							&.paypal {
								.icon {
									opacity: 1;
								}
							}
							&.pix {
								.icon {
									opacity: 1;
								}
							}
                            &.BANK{
                                .icon{
                                    opacity: 1;
                                }
                            }

							.footer {
								background-color: @theme-color;
								.coin-num {
									color: #ffffff;
								}
							}
							.main {
								border-color: @theme-color;
								&::after {
									background-image: url(../../assets/images/recharge_select_active.png);
								}
							}
						}
						&.paytm {
							.icon {
								background-image: url(../../assets/images/icon_paytm.svg);
								opacity: 0.3;
							}
						}
						&.paypal {
							.icon {
								background-image: url(../../assets/images/icon_paypal.svg);
								opacity: 0.3;
							}
						}
						&.pix {
							.icon {
								background-image: url(../../assets/images/icon_pix.svg);
								opacity: 0.3;
							}
						}
                        &.BANK{
                            .icon{
                                background-image: url(../../assets/images/icon_bank.png);
                                opacity: 0.3;
                            }
                        }
						.main {
							padding: 0.16rem 0.16rem 0.1rem;
							border: 0.02rem solid transparent;
							border-radius: 0.08rem 0.08rem 0 0;
							position: relative;
							.icon {
								height: 0.36rem;
								width: 0.72rem;
								background-repeat: no-repeat;
								background-size: contain;
								background-position: center;
							}
							.money {
								font-size: 0.16rem;
								font-weight: 500;
								line-height: 0.28rem;
								color: #555555;
								text-align: center;
								margin-top: 0.08rem;
							}
							&::after {
								position: absolute;
								right: -1px;
								top: -1px;
								content: "";
								display: block;
								height: 0.26rem;
								width: 0.32rem;
								background: url(../../assets/images/recharge_select_unactive.png)
									no-repeat center;
								background-size: contain;
							}
						}
						.footer {
							display: flex;
							align-items: center;
							justify-content: center;
							padding: 0.04rem 0 0.06rem;
							background-color: #f8f8f8;
							border-radius: 0 0 0.08rem 0.08rem;
							.coin-num {
								background: url(../../assets/images/icon_coin.svg)
									no-repeat left center;
								background-size: 0.2rem;
								padding-left: 0.22rem;
								font-size: 0.14rem;
								font-weight: 700;
								line-height: 0.24rem;
								color: #222222;
							}
						}
					}
				}
			}
			.desc {
				margin-top: 0.2rem;
				.tips {
					margin-top: 0.1rem;
					color: #ffca28;
					font-size: 0.14rem;
					font-weight: 400;
					line-height: 0.24rem;
				}
				.content {
					margin-top: 0.08rem;
					font-size: 0.12rem;
					font-weight: 400;
					color: #9c9da6;
					line-height: 0.2rem;
				}
			}
			.module {
				.title {
					font-size: 0.16rem;
					font-weight: 500;
					color: #121314;
					line-height: 0.28rem;
				}
			}
		}
		& > .footer {
			.button {
				.unique-button();
				border-radius: 0.12rem;
				font-size: 0.16rem;
				width: calc(100% - 0.32rem);
				height: 0.46rem;
				position: fixed;
				// bottom: .32rem;
				left: 50%;
				transform: translateX(-50%);
			}
		}
	}
}
</style>